<template>
  <div class="order-approval-page">
    <el-card>
      <template #header>
        <div class="page-header">
          <h3>订单审批</h3>
          <div class="header-stats">
            <el-badge :value="statistics.pending" :max="99" class="badge-item">
              <el-button>待审批</el-button>
            </el-badge>
            <el-badge :value="statistics.approved" :max="99" class="badge-item" type="success">
              <el-button>已审批</el-button>
            </el-badge>
            <el-badge :value="statistics.rejected" :max="99" class="badge-item" type="danger">
              <el-button>已拒绝</el-button>
            </el-badge>
          </div>
        </div>
      </template>

      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :model="searchForm" inline>
          <el-form-item label="订单号">
            <el-input v-model="searchForm.orderNo" placeholder="请输入订单号" clearable />
          </el-form-item>
          <el-form-item label="申请人">
            <el-input v-model="searchForm.applicant" placeholder="请输入申请人" clearable />
          </el-form-item>
          <el-form-item label="审批状态">
            <el-select v-model="searchForm.approvalStatus" placeholder="请选择审批状态" clearable>
              <el-option label="待审批" value="pending" />
              <el-option label="已审批" value="approved" />
              <el-option label="已拒绝" value="rejected" />
              <el-option label="审批中" value="processing" />
            </el-select>
          </el-form-item>
          <el-form-item label="紧急程度">
            <el-select v-model="searchForm.urgency" placeholder="请选择紧急程度" clearable>
              <el-option label="普通" value="normal" />
              <el-option label="紧急" value="urgent" />
              <el-option label="特急" value="critical" />
            </el-select>
          </el-form-item>
          <el-form-item label="申请时间">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 表格区域 -->
      <el-table :data="tableData" v-loading="loading" stripe>
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="orderNo" label="订单号" width="150">
          <template #default="{ row }">
            <el-link type="primary" @click="handleViewOrder(row)">
              {{ row.orderNo }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column prop="applicant" label="申请人" width="100" />
        <el-table-column prop="customerName" label="客户" width="150" />
        <el-table-column prop="totalAmount" label="订单金额" width="120">
          <template #default="{ row }">
            <span style="font-weight: bold; color: #f56c6c;">
              ¥{{ row.totalAmount.toFixed(2) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="urgency" label="紧急程度" width="100">
          <template #default="{ row }">
            <el-tag 
              :type="row.urgency === 'critical' ? 'danger' : row.urgency === 'urgent' ? 'warning' : 'info'"
              effect="dark"
            >
              {{ getUrgencyText(row.urgency) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="approvalStatus" label="审批状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getApprovalStatusType(row.approvalStatus)">
              {{ getApprovalStatusText(row.approvalStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="currentApprover" label="当前审批人" width="120" />
        <el-table-column prop="applyTime" label="申请时间" width="180" />
        <el-table-column prop="reason" label="申请原因" min-width="200" show-overflow-tooltip />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button 
              v-if="row.approvalStatus === 'pending' && row.currentApprover === '当前用户'" 
              type="success" 
              size="small" 
              @click="handleApprove(row)"
            >
              <el-icon><Check /></el-icon>
              通过
            </el-button>
            <el-button 
              v-if="row.approvalStatus === 'pending' && row.currentApprover === '当前用户'" 
              type="danger" 
              size="small" 
              @click="handleReject(row)"
            >
              <el-icon><Close /></el-icon>
              拒绝
            </el-button>
            <el-button 
              type="primary" 
              size="small" 
              @click="handleViewProgress(row)"
            >
              <el-icon><View /></el-icon>
              进度
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 审批对话框 -->
    <el-dialog
      v-model="approvalDialogVisible"
      :title="approvalAction === 'approve' ? '审批通过' : '审批拒绝'"
      width="600px"
    >
      <el-form
        ref="approvalFormRef"
        :model="approvalForm"
        :rules="approvalRules"
        label-width="100px"
      >
        <el-form-item label="订单号">
          <el-input v-model="currentOrder.orderNo" disabled />
        </el-form-item>
        <el-form-item label="申请人">
          <el-input v-model="currentOrder.applicant" disabled />
        </el-form-item>
        <el-form-item label="订单金额">
          <el-input :value="'¥' + currentOrder.totalAmount?.toFixed(2)" disabled />
        </el-form-item>
        <el-form-item label="申请原因">
          <el-input 
            v-model="currentOrder.reason" 
            type="textarea" 
            :rows="3"
            disabled 
          />
        </el-form-item>
        <el-form-item label="审批意见" prop="opinion">
          <el-input 
            v-model="approvalForm.opinion" 
            type="textarea" 
            :rows="4"
            :placeholder="approvalAction === 'approve' ? '请输入审批意见（选填）' : '请输入拒绝原因（必填）'"
          />
        </el-form-item>
        <el-form-item v-if="approvalAction === 'approve'" label="下一审批人" prop="nextApprover">
          <el-select v-model="approvalForm.nextApprover" placeholder="请选择下一审批人" style="width: 100%">
            <el-option label="财务经理" value="财务经理" />
            <el-option label="总经理" value="总经理" />
            <el-option label="董事长" value="董事长" />
            <el-option label="无需下级审批" value="" />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="approvalDialogVisible = false">取消</el-button>
        <el-button 
          :type="approvalAction === 'approve' ? 'success' : 'danger'" 
          @click="handleSubmitApproval"
          :loading="submitLoading"
        >
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 审批进度对话框 -->
    <el-dialog
      v-model="progressDialogVisible"
      title="审批进度"
      width="800px"
    >
      <div v-if="currentOrder">
        <el-steps :active="getActiveStep(currentOrder.approvalStatus)" finish-status="success" align-center>
          <el-step title="提交申请" :description="currentOrder.applyTime" />
          <el-step 
            v-for="(record, index) in currentOrder.approvalRecords" 
            :key="index"
            :title="`${record.approver} 审批`"
            :description="record.time"
            :status="record.status === 'approved' ? 'success' : record.status === 'rejected' ? 'error' : 'process'"
          />
          <el-step title="审批完成" />
        </el-steps>

        <el-divider>审批记录</el-divider>

        <el-timeline>
          <el-timeline-item
            v-for="(record, index) in currentOrder.approvalRecords"
            :key="index"
            :timestamp="record.time"
            :type="record.status === 'approved' ? 'success' : record.status === 'rejected' ? 'danger' : 'primary'"
            placement="top"
          >
            <el-card>
              <div class="approval-record">
                <div class="record-header">
                  <span class="record-title">
                    <el-icon v-if="record.status === 'approved'"><Check /></el-icon>
                    <el-icon v-if="record.status === 'rejected'"><Close /></el-icon>
                    {{ record.approver }} - {{ getApprovalStatusText(record.status) }}
                  </span>
                  <el-tag :type="record.status === 'approved' ? 'success' : record.status === 'rejected' ? 'danger' : 'warning'">
                    {{ record.role }}
                  </el-tag>
                </div>
                <div class="record-opinion">
                  审批意见：{{ record.opinion || '无' }}
                </div>
              </div>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-dialog>

    <!-- 订单详情对话框 -->
    <el-dialog
      v-model="orderDetailVisible"
      title="订单详情"
      width="900px"
    >
      <div v-if="currentOrder">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单号">{{ currentOrder.orderNo }}</el-descriptions-item>
          <el-descriptions-item label="客户">{{ currentOrder.customerName }}</el-descriptions-item>
          <el-descriptions-item label="订单金额">
            <span style="font-weight: bold; color: #f56c6c;">
              ¥{{ currentOrder.totalAmount?.toFixed(2) }}
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="申请人">{{ currentOrder.applicant }}</el-descriptions-item>
          <el-descriptions-item label="申请时间">{{ currentOrder.applyTime }}</el-descriptions-item>
          <el-descriptions-item label="紧急程度">
            <el-tag 
              :type="currentOrder.urgency === 'critical' ? 'danger' : currentOrder.urgency === 'urgent' ? 'warning' : 'info'"
            >
              {{ getUrgencyText(currentOrder.urgency) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="申请原因" :span="2">
            {{ currentOrder.reason }}
          </el-descriptions-item>
        </el-descriptions>

        <el-divider>商品明细</el-divider>
        <el-table :data="currentOrder.products" border>
          <el-table-column prop="productCode" label="商品编码" width="120" />
          <el-table-column prop="productName" label="商品名称" width="200" />
          <el-table-column prop="specification" label="规格" width="150" />
          <el-table-column prop="unit" label="单位" width="80" />
          <el-table-column prop="quantity" label="数量" width="100" />
          <el-table-column prop="unitPrice" label="单价" width="100">
            <template #default="{ row }">
              ¥{{ row.unitPrice.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="amount" label="金额" width="120">
            <template #default="{ row }">
              ¥{{ (row.quantity * row.unitPrice).toFixed(2) }}
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Check, Close, View } from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const approvalDialogVisible = ref(false)
const progressDialogVisible = ref(false)
const orderDetailVisible = ref(false)
const submitLoading = ref(false)
const approvalFormRef = ref()
const approvalAction = ref('approve')
const currentOrder = ref({})

// 统计数据
const statistics = reactive({
  pending: 15,
  approved: 128,
  rejected: 8
})

// 搜索表单
const searchForm = reactive({
  orderNo: '',
  applicant: '',
  approvalStatus: '',
  urgency: '',
  dateRange: []
})

// 审批表单
const approvalForm = reactive({
  opinion: '',
  nextApprover: ''
})

// 表单验证规则
const approvalRules = {
  opinion: [
    { 
      required: true, 
      message: '请输入审批意见', 
      trigger: 'blur',
      validator: (rule, value, callback) => {
        if (approvalAction.value === 'reject' && !value) {
          callback(new Error('拒绝时必须填写原因'))
        } else {
          callback()
        }
      }
    }
  ]
}

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 表格数据
const tableData = ref([
  {
    id: 1,
    orderNo: 'SO20240115001',
    applicant: '张三',
    customerName: '北京科技有限公司',
    totalAmount: 125000,
    urgency: 'critical',
    approvalStatus: 'pending',
    currentApprover: '当前用户',
    applyTime: '2024-01-15 10:00:00',
    reason: '大客户订单，金额较大，需要审批',
    products: [
      {
        productCode: 'P001',
        productName: 'iPhone 15',
        specification: '256GB 白色',
        unit: '台',
        quantity: 25,
        unitPrice: 5000
      }
    ],
    approvalRecords: []
  },
  {
    id: 2,
    orderNo: 'SO20240115002',
    applicant: '李四',
    customerName: '上海贸易公司',
    totalAmount: 85000,
    urgency: 'urgent',
    approvalStatus: 'processing',
    currentApprover: '财务经理',
    applyTime: '2024-01-15 11:00:00',
    reason: '新客户订单，需要走审批流程',
    products: [
      {
        productCode: 'P002',
        productName: 'MacBook Pro',
        specification: '16英寸 M3芯片',
        unit: '台',
        quantity: 5,
        unitPrice: 17000
      }
    ],
    approvalRecords: [
      {
        approver: '销售经理',
        role: '销售部',
        status: 'approved',
        opinion: '同意，客户信誉良好',
        time: '2024-01-15 11:30:00'
      }
    ]
  },
  {
    id: 3,
    orderNo: 'SO20240115003',
    applicant: '王五',
    customerName: '深圳电子公司',
    totalAmount: 65000,
    urgency: 'normal',
    approvalStatus: 'approved',
    currentApprover: '',
    applyTime: '2024-01-15 09:00:00',
    reason: '常规订单',
    products: [
      {
        productCode: 'P003',
        productName: 'iPad Pro',
        specification: '12.9英寸 256GB',
        unit: '台',
        quantity: 10,
        unitPrice: 6500
      }
    ],
    approvalRecords: [
      {
        approver: '销售经理',
        role: '销售部',
        status: 'approved',
        opinion: '同意',
        time: '2024-01-15 09:30:00'
      },
      {
        approver: '财务经理',
        role: '财务部',
        status: 'approved',
        opinion: '财务审核通过',
        time: '2024-01-15 10:00:00'
      }
    ]
  },
  {
    id: 4,
    orderNo: 'SO20240115004',
    applicant: '赵六',
    customerName: '广州商贸公司',
    totalAmount: 45000,
    urgency: 'normal',
    approvalStatus: 'rejected',
    currentApprover: '',
    applyTime: '2024-01-15 08:00:00',
    reason: '客户要求特殊价格',
    products: [
      {
        productCode: 'P001',
        productName: 'iPhone 15',
        specification: '128GB 黑色',
        unit: '台',
        quantity: 9,
        unitPrice: 5000
      }
    ],
    approvalRecords: [
      {
        approver: '销售经理',
        role: '销售部',
        status: 'approved',
        opinion: '同意',
        time: '2024-01-15 08:30:00'
      },
      {
        approver: '财务经理',
        role: '财务部',
        status: 'rejected',
        opinion: '价格低于成本价，不予批准',
        time: '2024-01-15 09:00:00'
      }
    ]
  }
])

// 方法
const getUrgencyText = (urgency) => {
  const map = {
    normal: '普通',
    urgent: '紧急',
    critical: '特急'
  }
  return map[urgency] || '普通'
}

const getApprovalStatusText = (status) => {
  const map = {
    pending: '待审批',
    processing: '审批中',
    approved: '已审批',
    rejected: '已拒绝'
  }
  return map[status] || status
}

const getApprovalStatusType = (status) => {
  const map = {
    pending: 'warning',
    processing: 'primary',
    approved: 'success',
    rejected: 'danger'
  }
  return map[status] || 'info'
}

const getActiveStep = (status) => {
  const map = {
    pending: 1,
    processing: 2,
    approved: 3,
    rejected: 3
  }
  return map[status] || 1
}

const loadData = () => {
  loading.value = true
  setTimeout(() => {
    pagination.total = tableData.value.length
    loading.value = false
  }, 500)
}

const handleSearch = () => {
  pagination.currentPage = 1
  loadData()
}

const handleReset = () => {
  Object.assign(searchForm, {
    orderNo: '',
    applicant: '',
    approvalStatus: '',
    urgency: '',
    dateRange: []
  })
  handleSearch()
}

const handleApprove = (row) => {
  currentOrder.value = row
  approvalAction.value = 'approve'
  approvalDialogVisible.value = true
  resetApprovalForm()
}

const handleReject = (row) => {
  currentOrder.value = row
  approvalAction.value = 'reject'
  approvalDialogVisible.value = true
  resetApprovalForm()
}

const handleViewProgress = (row) => {
  currentOrder.value = row
  progressDialogVisible.value = true
}

const handleViewOrder = (row) => {
  currentOrder.value = row
  orderDetailVisible.value = true
}

const handleSubmitApproval = async () => {
  if (!approvalFormRef.value) return

  try {
    await approvalFormRef.value.validate()

    if (approvalAction.value === 'reject' && !approvalForm.opinion) {
      ElMessage.warning('拒绝时必须填写原因')
      return
    }

    submitLoading.value = true

    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))

    const index = tableData.value.findIndex(item => item.id === currentOrder.value.id)
    if (index > -1) {
      const newRecord = {
        approver: '当前用户',
        role: '部门经理',
        status: approvalAction.value === 'approve' ? 'approved' : 'rejected',
        opinion: approvalForm.opinion,
        time: new Date().toLocaleString()
      }

      tableData.value[index].approvalRecords.push(newRecord)

      if (approvalAction.value === 'approve') {
        if (approvalForm.nextApprover) {
          tableData.value[index].approvalStatus = 'processing'
          tableData.value[index].currentApprover = approvalForm.nextApprover
        } else {
          tableData.value[index].approvalStatus = 'approved'
          tableData.value[index].currentApprover = ''
        }
        ElMessage.success('审批通过')
      } else {
        tableData.value[index].approvalStatus = 'rejected'
        tableData.value[index].currentApprover = ''
        ElMessage.success('审批拒绝')
      }

      statistics.pending--
      if (approvalAction.value === 'approve') {
        if (!approvalForm.nextApprover) {
          statistics.approved++
        }
      } else {
        statistics.rejected++
      }
    }

    approvalDialogVisible.value = false
    loadData()
  } catch (error) {
    console.error('审批失败:', error)
  } finally {
    submitLoading.value = false
  }
}

const resetApprovalForm = () => {
  Object.assign(approvalForm, {
    opinion: '',
    nextApprover: ''
  })
  approvalFormRef.value?.clearValidate()
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  loadData()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadData()
}

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.order-approval-page {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-header h3 {
  margin: 0;
  color: #303133;
}

.header-stats {
  display: flex;
  gap: 12px;
}

.badge-item {
  cursor: pointer;
}

.search-area {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 4px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.approval-record {
  padding: 8px;
}

.record-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.record-title {
  font-weight: bold;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 8px;
}

.record-opinion {
  color: #606266;
  font-size: 14px;
  line-height: 1.6;
}
</style>

